<template>
  <div>
    <page-loading
      :loading.sync="pageLoading"
      :error.sync="pageError"
      :enable-pull-refresh="false"
      @reload="init"
    >
      <template v-if="hasInfo">
        <div v-if="banner" class="banner">
          <img class="img" :src="banner" />
        </div>
        <div class="title-wrap">
          <h1 class="title">{{ articleInfo.title }}</h1>
          <div class="info">
            <span v-if="type" class="type">{{ type }}</span>
            <span v-if="time" class="time">{{ time | formatDate }}</span>
            <span v-if="view" class="view">{{ view | formatNumber }}阅读</span>
          </div>
        </div>
        <div v-if="author" class="author-wrap" @click="toSpace">
          <user-avatar
            class="face"
            size="sm"
            :url="author.face"
            :vip-status="author.vip.vipStatus"
            :official="author.official_verify"
          />
          <span class="name">{{ author.name }}</span>
          <van-button class="follow" size="small" :disabled="author.is_followed">{{ author.is_followed ? '已关注' : '关注'}}</van-button>
        </div>
        <article-content
          :content="content"
          :tags="tags"
          :favorite="articleInfo.stats.favorite"
          :like="articleInfo.stats.like"
          :share="articleInfo.stats.share"
          :share-title="articleInfo.title"
          :share-pic="banner"
        />
        <article-more
          v-if="moreArticles"
          :articles="moreArticles"
        />
        <article-comment
          class="comment-wrap"
          v-if="comments"
          :comments="comments"
        />
      </template>
    </page-loading>
  </div>
</template>

<script>
import PageLoading from '@/components/page-loading/PageLoading.vue'
import UserAvatar from '@/components/user-avatar/UserAvatar.vue'
import ArticleContent from '@/components/article/ArticleContent.vue'
import ArticleMore from '@/components/article/ArticleMore.vue'
import ArticleComment from '@/components/comment/Comment.vue'
import { Button as VanButton } from 'vant'
import pageLoadingMixin from '@/mixins/pageLoading.js'
import { apiGetArticleContent, apiGetArticleAbout, apiGetVideos, apiGetMoreArticle, apiGetComments } from '@/api/article.js'
import { formatDate, formatNumber } from '@/filters/filters.js'
export default {
  name: 'Article',
  inject: ['rootRouter', 'rootTitle', 'rootKeyword', 'rootDescription'],
  mixins: [pageLoadingMixin],
  metaInfo () {
    return {
      title: this.title,
      meta: [
        { name: 'keywords', content: this.rootKeyword },
        { name: 'description', content: this.rootDescription }
      ]
    }
  },
  components: {
    PageLoading,
    UserAvatar,
    VanButton,
    ArticleContent,
    ArticleMore,
    ArticleComment
  },
  props: {
    id: {
      type: [Number, String]
    }
  },
  data () {
    return {
      articleInfo: null,
      type: null,
      time: null,
      content: null,
      author: null,
      tags: null,
      videoIds: null,
      videos: null,
      moreArticles: null,
      comments: null
    }
  },
  computed: {
    hasInfo () {
      return this.articleInfo !== null
    },
    title () {
      let word = this.rootTitle
      if (this.hasInfo) {
        word = `${this.articleInfo.title}_${word}`
      }
      return word
    },
    banner () {
      return this.hasInfo ? (this.articleInfo.banner_url ? this.articleInfo.banner_url : '') : ''
    },
    view () {
      let view = 0
      if (this.hasInfo) {
        view = this.articleInfo.stats.view
      }
      return view
    }
  },
  watch: {
    id (newVal) {
      this.pageError = false
      this.init()
    },
    videoIds (newVal) {
      if (newVal) {
        this.getVideos()
      }
    }
  },
  filters: {
    formatNumber,
    formatDate
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this.getData()
      this.getContent()
      this.getMore()
      this.getComment()
    },
    getData () {
      apiGetArticleAbout({ id: this.id }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          this.articleInfo = data
        } else {
          this.pageError = true
        }
      }).catch(err => {
        console.log(err)
        this.pageError = true
      }).finally(() => {
        this.pageLoading = false
      })
    },
    getContent () {
      apiGetArticleContent({ id: this.id }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { type, timestamp, content, videoIds, tags } = data
          this.type = type
          this.time = timestamp
          this.content = content
          this.tags = tags
          this.videoIds = videoIds
        }
      })
    },
    getVideos () {
      apiGetVideos({ id: this.id, videoIds: this.videoIds.join(',') }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          this.videos = data
          for (const value of this.videoIds.values()) {
            const ids = value.split(',')
            const htms = []
            for (const id of ids.values()) {
              htms.push(this.parseVideo(data[id]))
            }
            this.content = this.content.replace(`<i data-ids="${value}"></i>`, htms.join(''))
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getMore () {
      apiGetMoreArticle({ id: this.id }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { articles, author } = data
          this.moreArticles = articles
          this.author = author
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getComment () {
      apiGetComments({ id: this.id }).then(res => {
        const { code, data } = res
        if (code === 0 && data !== null) {
          const { replies } = data
          this.comments = replies
        }
      }).catch(err => {
        console.log(err)
      })
    },
    toSpace () {
      this.rootRouter.push({ name: 'space', params: { mid: this.author.mid } })
    },
    parseVideo (video) {
      // <div class="play-wrap"><i class="fa fa-play"></i></div>
      const html = `
        <div class="video-item">
          <a class="video-link" data-bvid="${video.bvid}"></a>
          <div class="video-cover">
            <img class="img video-img" src="${video.pic}@300w_188h" />
          </div>
          <div class="video-info">
            <div class="video-title">${video.title}</div>
            <div class="video-author">
              <i class="fa fa-up-zhu"></i>
              <span class="name">${video.owner.name}</span>
            </div>
          </div>
        </div>
      `
      return html
    }
  }
}
</script>
<style lang="scss" scoped>
  .banner{
    @include cover(375, 210);
    background: {
      color: $color-grey;
      size: 36%;
      image: url('~@/assets/placeholder.png');
      repeat: no-repeat;
      position: 50%;
    }
  }
  .title-wrap{
    padding: rem(15px) rem(16px) rem(20px);
    .title{
      font-size: rem(28px);
      color: $color-text-primary;
      margin: 0;
      margin-bottom: rem(10px);
      line-height: 1.4;
    }
    .info {
      font-size: rem(12px);
      color: $color-text-secondary;
      span{
        margin-right: rem(4px);
      }
    }
  }
  .author-wrap{
    display: flex;
    align-items: center;
    padding: rem(14px);
    .face{
      margin-right: rem(10px);
    }
    .name{
      flex: 1;
      color: $color-text-regular;
      font-size: rem(16px);
    }
    .follow{
      background-color: $theme-color;
      color: $color-white;
    }
  }
  .comment-wrap{
    border-top: 20px solid #f3f4f4;
  }
</style>
